package org.kalai.unifypay.pay;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.kalai.unifypay.Constant;
import org.kalai.unifypay.chanpay.Chanpay;
import org.kalai.unifypay.util.CipherUtils;
import org.kalai.unifypay.util.DataDao;
import org.kalai.unifypay.util.HttpUtil;
import org.kalai.unifypay.util.StringUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class Biz3003 implements Biz {

   private static final Logger logger = Logger.getLogger(Biz3003.class);

   @Override
   public Map<String, Object> pay(String tranxSN, long cent, String subject, String notifyUrl, String merchantCode, String bizData) {
      JSONObject jo = JSON.parseObject(bizData);
      if (jo == null)
         throw new RuntimeException("#211-bizData不能为空");
      /* 银行卡相关信息 */
      String phoneNo = jo.getString("phoneNo");// 手机号码
      String customerName = jo.getString("customerName");// 姓名
      String cerdId = jo.getString("cerdId");// 身份证号码
      String acctNo = jo.getString("acctNo");// 银行卡号
      String cvn2 = jo.getString("cvn2");// 信用卡背后三位数
      /* 信用卡有效期转换格式 */
      String expDate = jo.getString("expDate");
      if (StringUtil.isNotEmpty(expDate)) {
         expDate = expDate.substring(2) + "/" + expDate.substring(0, 2);
      }

      if (StringUtil.isEmpty(phoneNo, customerName, cerdId, acctNo)) {
         logger.info("信用卡六要素不能为空：" + bizData);
         throw new RuntimeException("#211-银行卡4要素不能为空");
      }
      /* 四要素验证 */
      Map<String, Object> params = new HashMap<>();
      params.put("PARTNER_NO_", "1001");
      params.put("CARD_NO_", acctNo);
      params.put("CARD_NAME_", customerName);
      params.put("CARD_MOBILE_", phoneNo);
      params.put("CARD_IDTYPE_", "01");
      params.put("CARD_IDCARD_", cerdId);
      params.put("SIGN_", CipherUtils.encryptMD5(acctNo + "A84632CED6B3BF021001").toLowerCase());

      String fourys = HttpUtil.sendPost("http://115.231.102.206:7007/cardval/validationCard.do", params);
      jo = JSON.parseObject(fourys);
      if (!"00".equals(jo.getString("code"))) {
         logger.error("无卡支付四要素验证失败：" + fourys);
         throw new RuntimeException("#10-无卡支付四要素验证失败");
      }
      /* 查询卡bin */
      JSONObject jsonResult = JSON.parseObject(request(Constant.BD_SECRET_URL, acctNo));
      if (!jsonResult.get("status").equals(1)) {
         logger.error(String.format("查询银行卡bin为空,[acctNo=%s]", acctNo));
         throw new RuntimeException("#213-此银行卡不支持快捷交易");
      }
      JSONObject json = (JSONObject) jsonResult.get("data");
      String cardtype = json.getString("cardtype");// 银行卡类型
      String bankname = json.getString("bankname");// 银行卡名称
      /* 获取银行简称代码 */
      String shortCode = DataDao.getInstance().getShortCodeByBankName(bankname, cardtype);
      if (StringUtil.isEmpty(shortCode)) {
         logger.error(String.format("查询银行简称代码信息为空,[bankName=%s][cardType=%s]", bankname, cardtype));
         throw new RuntimeException("#213-此银行卡不支持快捷交易");
      }

      return Chanpay.quickPayment(tranxSN, cent / 100.0, subject, customerName, cerdId, phoneNo, acctNo, cvn2, expDate, cardtype,
            shortCode);

   }

   @Override
   public void afterPay(String tranxSN, String respCode, String respDesc, String transAmt) {
   }

   public static void main(String[] args) {
      String jsonResult = request(Constant.BD_SECRET_URL, "6222520174331161");
      JSONObject jo = JSON.parseObject(jsonResult);
      JSONObject jo2 = (JSONObject) jo.get("data");
      System.out.println(jo2.get("cardtype") + jsonResult);
   }

   /**
    * @param urlAll
    *           :请求接口
    * @param httpArg
    *           :参数
    * @return 返回结果
    */
   public static String request(String httpUrl, String httpArg) {
      BufferedReader reader = null;
      String result = null;
      StringBuffer sbf = new StringBuffer();
      httpUrl = httpUrl + "?cardnum=" + httpArg;

      try {
         URL url = new URL(httpUrl);
         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
         connection.setRequestMethod("GET");
         // 填入apikey到HTTP header
         connection.setRequestProperty("apikey", Constant.BD_APIKEY);
         connection.connect();
         InputStream is = connection.getInputStream();
         reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
         String strRead = null;
         while ((strRead = reader.readLine()) != null) {
            sbf.append(strRead);
            sbf.append("\r\n");
         }
         reader.close();
         result = sbf.toString();
      } catch (Exception e) {
         e.printStackTrace();
      }
      return result;
   }
}
